package com.lihaozhe.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.lihaozhe.controller.CodeController;
import com.lihaozhe.handler.LoginAuthenticationFailureHandler;
import com.lihaozhe.security.exception.ValidateCodeException;
import com.lihaozhe.security.util.AuthenticationStoreUtil;
import com.lihaozhe.util.string.StringUtil;
import com.lihaozhe.util.token.CodeInSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author 李昊哲
 * @version 1.0.0
 * 2021/12/16 11:54
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ValidateCaptchaFilter extends OncePerRequestFilter {
    private final LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().contains("/login") && request.getMethod().equalsIgnoreCase("post")) {
            // 只用post提交登录请求才校验
            try {
                validate(request);
            } catch (ValidateCodeException e) {
                // 如果捕获到校验异常那么我们调用自定义登录handler
                loginAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        // 如果不是登录请求我就直接交给下一个过滤器
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) throws ValidateCodeException {
        HttpSession session = request.getSession();
        // 获取session中验证码信息
        CodeInSession codeInSession = (CodeInSession) session.getAttribute(CodeController.verificationCodeInSession);
        if (codeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        // 页面验证码初始值
        String verificationCode = "";
        String contentType = request.getContentType();
        // 获取页面传递过来的验证码
        if (!StringUtil.isBlank(contentType) && contentType.contains("application/json")) {
            // json传值 从请求头中获取验证码
            verificationCode = request.getHeader("verificationCode");
            if(StringUtil.isBlank(verificationCode)){
                throw new ValidateCodeException("验证码的值不能为空");
            }
        } else {
            // 表单传值
            verificationCode = request.getParameter("verificationCode");
            if (StringUtil.isBlank(verificationCode)) {
                throw new ValidateCodeException("验证码的值不能为空");
            }
        }
        String code = codeInSession.getCode();
        if (StringUtil.isBlank(code)) {
            throw new ValidateCodeException("验证码的已过期");
        }
        log.info("code >>> {}", code);
        log.info("verificationCode >>> {}", verificationCode);
        if (!code.equals(verificationCode)) {
            throw new ValidateCodeException("验证码不匹配");
        }
    }


    /**
     * 保存用户名和密码
     *
     * @param username 帐号/邮箱/手机号
     * @param password 密码/验证码
     */
    private void storeAuthentication(String username, String password) {
        AuthenticationStoreUtil.setUsername(username);
        AuthenticationStoreUtil.setPassword(password);
    }
}
